package com.pocket.demo.core.mybatis;

import com.pocket.demo.base.api.BaseDO;
import com.pocket.demo.core.context.UserContext;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.time.LocalDateTime;
import java.util.Properties;

/**
 * @author cookie. 【demo-MybatisPlus-3.1】
 **/
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class })
})
public class CommonPropertiesInterceptor implements Interceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonPropertiesInterceptor.class);

    private static final String SET_CREATOR = "setCreator";
    private static final String SET_CREATED_TIME = "setCreateTime";
    private static final String SET_UPDATER = "setUpdater";
    private static final String SET_UPDATED_TIME = "setUpdateTime";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement)args[0];
        Object parameter = args[1];
        if (ms.getSqlCommandType().equals(SqlCommandType.INSERT)) {
            fillAddProperties(parameter);
        } else if (ms.getSqlCommandType().equals(SqlCommandType.UPDATE)) {
            fillUpdateProperties(parameter);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }

    private void fillAddProperties(Object object) throws InvocationTargetException, IllegalAccessException {
        if (object == null || !(object instanceof BaseDO)) {
            return;
        }
        Method setCreator = ReflectionUtils.findMethod(object.getClass(), SET_CREATOR, new Class[] { String.class });
        Method setCreatedTime = ReflectionUtils.findMethod(object.getClass(), SET_CREATED_TIME, new Class[] { LocalDateTime.class });
        invoke(setCreatedTime, object, new LocalDateTime[]{ LocalDateTime.now() });
        invoke(setCreator, object, new Long[]{UserContext.getUserId()});
    }

    private void fillUpdateProperties(Object object) throws InvocationTargetException, IllegalAccessException {
        if (object == null || !(object instanceof BaseDO)) {
            return;
        }
        Method setUpdatedBy = ReflectionUtils.findMethod(object.getClass(), SET_UPDATER, new Class[] { String.class });
        Method setUpdatedAt = ReflectionUtils.findMethod(object.getClass(), SET_UPDATED_TIME, new Class[] { LocalDateTime.class });
        invoke(setUpdatedAt, object, new LocalDateTime[] { LocalDateTime.now() });
        invoke(setUpdatedBy, object, new Long[] { UserContext.getUserId() });
    }

    public void invoke(Method method, Object obj, Object... args) throws InvocationTargetException, IllegalAccessException {
        if (method == null) {
            return;
        }
        if (!Modifier.isPublic(method.getModifiers()) && !method.canAccess(obj)) {
            try {
                method.setAccessible(true);
            } catch (SecurityException e) {
                LOGGER.warn(e.getMessage(), e);
                return;
            }
        }
        method.invoke(obj, args);
    }
}
